package com.lcy.web.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by loucunyin on 2016/12/8 0008.
 * Http 请求、响应中的通用方法
 */
public class HttpUtils {
    public static String getIp(HttpServletRequest request){
        String defaultIp = "127.0.0.1";
        if(request == null){
            return defaultIp;
        }

        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (CommonUtils.isValidIp(ip)) {
            return ip;
        } else {
            return defaultIp;
        }
    }

    public static String getAgent(HttpServletRequest request){
        if(request == null){
            return null;
        }
        return request.getHeader("user-agent");
    }
}
